<!--
游戏详情页:
this.$router.push({path: '/game/gamedetail', query: {gameId: this.gameId}}); -->
<template>
  <div class="wrap">
    <header-top :option="headerOption"></header-top>
    <div class="x-bg game-details">
      <game-detail-overview :overview="game" :shutup='!isTalkTime' v-if='game.GAME_ID' :comment='comment'></game-detail-overview>
      <div class="comments" v-if='game.GAME_STEP != "5" && game.GAME_STEP != "4"'>
        <div class="content relative" v-if="comment!=null && comment.COMMUNITY_CONTENT!=null">
            <img class="user-head" :src="comment.USER_HEAD">
            <img class="loudspeaker" src="../../assets/images/dalaba@2x.png">
            <div class="xbb">
                <div class="up clearfix">
                    <div class="nickname">
                        用户<span>{{ comment.NICKNAME }}</span>刚发表评论
                    </div>
                    <div class="dataTime">{{ comment.dataTime }}</div>
                </div>
                <div class="down" v-html="comment.COMMUNITY_CONTENT"></div>
            </div>
        </div>
      </div>
      <game-detail-ranking :gameAttendPerson="game.GAME_ATTEND_PERSON + ''" :gameMaxLimit="game.GAME_MAX_LIMIT + ''" :gameStep="game.GAME_STEP" :gameId="game.GAME_ID" :gameName="game.GAME_NAME" :identity="game.identity" ></game-detail-ranking>
      <game-detail-player-list :players="game" v-if='game.GAME_ID != null || game.GAME_ID != undefined'></game-detail-player-list>
      <div class="history-comments"  :class="showEmoji?'history-comments-show':'history-comments'">
        <img src="../../assets/images/pinglunqu.png" v-if="showSpeak" @click="showComment">
        <img src="../../assets/images/jingcai.png" v-if="!showSpeak" @click="showComment">
      </div>
      <speak class='speak' ref='speak' v-show='showSpeak' :options='speakOptions' @speaking='onSpeaking' @emojiVisible='onEmojiVisible' />
    </div>
  </div>
</template>
<style scoped>
.game-details{
  /*overflow: auto;
  -webkit-overflow-scrolling: touch;
  position: absolute;
  top: 44px;
  bottom: 0;
  width: 100%;*/
}
</style>
<script>

import Constant from 'common/constant'
import HeaderTop from 'components/HeaderTop'
import CommonUtil from 'common/common.util'
import RemoteDAO from 'common/remoteDAO'
import LocalDAO from 'common/localDAO'
import Emoji from 'components/game/comment/Emoji'
import $ from 'jquery'
import GameDetailOverview from 'components/game/detail/GameDetailOverview'
import GameDetailRanking from 'components/game/detail/GameDetailRanking'
import GameDetailPlayerList from 'components/game/detail/GameDetailPlayerList'
import Speak from 'components/game/comment/Speak'
import cutNumber from 'filters/cutNumber'
import isInTalkTime from 'filters/isInTalkTime'
import filterGameStage from 'filters/filterGameStage'
import {getSessionGame, saveSessionGame} from 'components/game/openGame'
export default {
  components: {
    HeaderTop,Speak,
    'game-detail-overview':GameDetailOverview,
    'game-detail-ranking':GameDetailRanking,
    'game-detail-player-list':GameDetailPlayerList,
    'emoji':Emoji,
  },
  filters: {
    cutNumber, isInTalkTime, filterGameStage
  },
  data () {
    return {
      showSpeak:false,//是否允许聊天
      isTalkTime: true,
      showEmoji: false,
      ranking: [],
      comment: null,
      game: {//当前比赛的基本信息
        GAME_ID: undefined,
        identity: Constant.game.identity.ONLOOKER,//用户在该比赛的身份
        GAME_STEP: '0'
      },
      communityContent:"",
      talkTime:[
          {
              b: '09:00:00',//begin
              e: '17:00:00'//end
          }
      ],
      headerOption: {
          title: '',
          leftBtn: Constant.leftBtn.BACK,
          operations: [Constant.operation.GAME_RULES, Constant.operation.SHARE],
          page: Constant.storage.SHARE_GAME_DETAILS
      },
      userCode: "",
      test:"",
      speakOptions: {
        userCode: '',
        userHead: '',
        nickName: '',
        objectType: 4,
        topicCode: '',
        topicName: '',
        style: '#f2f2f2'
      }
    }
  },
  mounted () {
    this.$store.dispatch('setLoading', {visible: true});
    this.init();
  },
  destroyed(){
    this.$store.dispatch('setLoading', {visible: false});
  },
  methods: {
    init() {
      this.speakOptions.userCode = LocalDAO.getUserCode();
      this.speakOptions.nickName = LocalDAO.getNickname();
      this.speakOptions.userHead = LocalDAO.getUserHead();
      this.speakOptions.topicCode = this.$route.query.gameId;
      this.TD("12001",this.speakOptions.userCode);// 埋点

      var sGame = getSessionGame(this.speakOptions.topicCode);
      if(sGame != null) {
        Object.assign(this.game, sGame);
        this.setHeader();
      }
      this.getGame(this.speakOptions.topicCode, this.speakOptions.userCode);
      this.loadcomment(this.speakOptions.topicCode,this.speakOptions.userCode);
    },
    /**
     * 用户发送了消息
     * @param  {Object} msg {
     *                       type: 1,//1位表情，其他值为文本
     *                       path:'url',//表情的地址，仅当type值为1时
     *                       text:'word',//用户发表的内容，如果type=1，则该值为}
     * @return {[type]}     [description]
     */
    onSpeaking(msg){
      this.comment = msg;
      this.comment.USER_HEAD = this.speakOptions.userHead;
      this.comment.NICKNAME = this.speakOptions.nickName;
      this.comment.dataTime = msg.COMMUNITY_DATE + ' '+ msg.COMMUNITY_TIME;
      this.comment.COMMUNITY_CONTENT = '“'+this.$refs.speak.str2Emoji(unescape(msg.text.replace(/\\u/g, '\%u'))) + '“';
    },
    onEmojiVisible(visible){
      this.showEmoji = visible;
    },
    checkIsPlayer(gameId, userCode){
      if(gameId == null || gameId == undefined || gameId == ''){
        this.$store.dispatch('setTip', {text:'gameId is '+ gameId});
        return;
      }
      if(userCode == null || userCode == undefined || userCode == ''){
        return;
      }
      RemoteDAO.callUC12008303(userCode, "1", "200", "1", "0", "", response => {
        if(response.error != '0'){
          this.$store.dispatch('setTip', {text: response.data});
          return;
        }else{
          response.data.body.forEach(item => {
            if(item.GAME_ID == gameId){
              this.game.identity = Constant.game.identity.PLAYER;
              return false;
            }
          });
        }
        this.loadSpeak();
      });
    },
    getGame(gameId, userCode){
    	let param = {
        userCode: userCode,
        gameId: gameId,
        gameStatus: '',
        gameKind: '',
        pageSize: '1',
        pageNum: '1'
      }
      RemoteDAO.callUC12008302(param, response => {
        if(response.error != '0') {
          this.$store.dispatch('setTip', {text: response.data});
          this.$store.dispatch('setLoading', {visible: false});
          return;
        }
        if(response.data.body.length > 0){
          Object.assign(this.game, response.data.body[0]);
          this.speakOptions.topicName = this.game.GAME_NAME;
          this.setHeader();
          this.checkIsPlayer(this.speakOptions.topicCode, this.speakOptions.userCode);
          this.updateShareInfo();
          saveSessionGame(this.game);
        }
        this.$store.dispatch('setLoading', {visible: false});
      });
    },
    /**
     * 重置headerOption
     */
    setHeader(){
      this.headerOption.title = this.game.GAME_NAME;
      if(this.game.GAME_TYPE == 'CLS'){
        this.headerOption.operations = [ Constant.operation.HUGE_GAME_RULES, Constant.operation.SHARE ];
      }else if(this.game.GAME_TYPE == 'JYS'){
        this.headerOption.operations = [ Constant.operation.JYS_GAME_RULES, Constant.operation.SHARE ];
      } else if (this.game.GAME_ID === '201707270050005203' || this.game.GAME_NAME === '甜橙理财校园股神大赛第一季' || this.game.GAME_NAME === '甜橙理财校园股神大赛第二季') {
        this.headerOption.operations = [Constant.operation.SHARE]
      }
    },
    updateShareInfo(){
      var shareGameDetails = LocalDAO.getShareGameDetails();
      shareGameDetails.ranking = {
        gameStage: filterGameStage(this.game.GAME_STEP),
        gameStep: this.game.GAME_STEP,
        identity: this.game.identity, 
        gameAttendPerson: this.game.GAME_ATTEND_PERSON,
        gameMaxLimit: this.game.GAME_MAX_LIMIT, 
        gameId: this.game.GAME_ID, 
        gameName: this.game.GAME_NAME
      }
      shareGameDetails.overview = {
        gameId: this.game.GAME_ID,
        gameStage: filterGameStage(this.game.GAME_STEP),
        identity: this.game.identity,
        gameAmount: cutNumber(this.game.GAME_AMOUNT),
        gameKind: this.game.GAME_KIND,
        gameType: this.game.GAME_TYPE,
        gameAttendPerson: this.game.GAME_ATTEND_PERSON,
        gameMaxLimit: this.game.GAME_MAX_LIMIT,
        gameName: this.game.GAME_NAME,
        currentUserCode: this.game.currentUserCode,
        gamePWD: this.game.GAME_PWD,
        beginDate: this.game.BEGIN_DATE,
        endDate: this.game.END_DATE,
        gameNeedAmount: parseInt(this.game.GAME_NEED_AMOUNT),
        createrCompany: this.game.CREATER_COMPANY,
        createrNickname: this.game.CREATER_NICKNAME,
        createrHead: this.game.CREATER_HEAD,
        isGamePWD: this.game.IS_GAMEPWD,
        createUser: this.game.CREATE_USER
      }
      shareGameDetails.players = shareGameDetails.overview
      shareGameDetails.players.list = []
      shareGameDetails.adDownload = {userCode: this.speakOptions.userCode};
      LocalDAO.setShareGameDetails(shareGameDetails);
    },
    TD(code,userCode){
      try{
        TDAPP.onEvent(code, "",  {"usercode":userCode});
        TDAPP.send();
      }catch(err){
        console.warn(err);
      }
    },
    loadSpeak(){
      if((this.game.GAME_STEP == '1' || this.game.GAME_STEP == '2' || this.game.GAME_STEP == '3') && this.game.identity == Constant.game.identity.PLAYER){
    	  CommonUtil.getTalkTime(data=> {
           	this.talkTime = data;
           	this.checkTime();
        });
      }
    },
    checkTime(){
    	// 获取交易日
      RemoteDAO.getTradeDate(response=> {
        if (response.error == "0") {
          // 返回交易日字符串
          var tradeDate = new Date(this.transferFormatDate(response.data.body[0].next_trade_date, '/'));
          // 获取服务器时间
          RemoteDAO.callGT1008(response=> {
            if (response.error == "0") {
              var nowDate = new Date(this.transferFormatDate(response.data.body.date, '/'));
              var nowTime = CommonUtil.formatTime(response.data.body.time).split(':');
              nowDate.setHours(nowTime[0], nowTime[1], nowTime[2]);
              this.showSpeak = isInTalkTime(nowDate, tradeDate, this.talkTime);
              this.isTalkTime = this.showSpeak;
            }
          });
        } else {
          this.$store.dispatch('setTip',{text:response.data});
          this.showSpeak = false;
        }
      });
    },
    transferFormatDate(str, separator) {
      if(str == undefined || str == null || str.length < 8) return '0000'+separator+'00'+separator+'00';
      str += '';
      var year = str.substring(0,4);
      var month = str.substring(4,6);
      if(month.length <= 0) month = '01';
      var day = str.substring(6,8);
      if(day.length <= 0) day = '01';
      return year+separator+month+separator+day;
  	},
    showComment(){
 			this.$router.push({path: '/game/comment', query: {topicCode: this.game.GAME_ID, topicName:this.game.GAME_NAME, objectType:4, identity:this.game.identity, gameStep:this.game.GAME_STEP}})
		},
    loadcomment(gameId,userCode){
      var params = {
        USER_CODE: userCode,
        ID: gameId,
        PAGE_SIZE: "1",
        PAGE_NO: "1",
        QUERY_FLAG: "0"
      };
      RemoteDAO.callUC12008318(params, response=> { // 必须传 0，才能查到其他人的
        if (response.error == "0") {
          if(response.data.body.length > 0){
            this.comment = this.filterMsg(response.data.body[0]);
          }
        }
      });
    },
    filterMsg(msg){
      msg.NICKNAME = msg.NICKNAME.length <= 8 ? msg.NICKNAME : msg.NICKNAME.substring(0, 8) + '...';
      if(msg.USER_HEAD == '') msg.USER_HEAD = CommonUtil.getDefaultUserHead(msg.USER_CODE);
      msg.COMMUNITY_DATE = CommonUtil.formatDatePoint(msg.COMMUNITY_DATE);
      msg.COMMUNITY_TIME = CommonUtil.formatHourMinute(msg.COMMUNITY_TIME);
      msg.COMMUNITY_CONTENT = unescape(msg.COMMUNITY_CONTENT.replace(/\\u/g, '\%u'));
      msg.COMMUNITY_CONTENT = '“'+ this.$refs.speak.str2Emoji(msg.COMMUNITY_CONTENT) + '”';
      if (msg.COMMUNITY_DATE == CommonUtil.getTodayFormatDate()) {
        msg.dataTime = "今天 " + CommonUtil.formatHourMinute(msg.COMMUNITY_TIME);
      } else {
        let position = msg.COMMUNITY_DATE.indexOf(".");
        if ( position >= 0) { // 只取月、日
          msg.COMMUNITY_DATE = msg.COMMUNITY_DATE.substring(position + 1);
        }
        msg.dataTime = msg.COMMUNITY_DATE + " " + msg.COMMUNITY_TIME;
      }
      return msg;
    }
  }
}
</script>


